package com.hzcc.hzccblog.interceptor;

import com.hzcc.hzccblog.utils.JWTUtil;
import com.hzcc.hzccblog.utils.RedisUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

import static com.hzcc.hzccblog.common.Constant.LOGIN_TOKEN;

/**
 * @Author 早睡蛋
 * @Date 2022/7/17 17:12:32
 * @Desc:登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        try {
            System.out.println(token);
            if (token==null || token==""){
                response.setStatus(4001);
                return false;
            }

            String userToken = token.substring(0,token.length()-1);
            System.out.println(userToken);
            Map<String, Object> stringObjectMap = JWTUtil.verify1(userToken);
            String email = (String) stringObjectMap.get("email");
            System.out.println(email);
            boolean b = redisUtil.existsString(LOGIN_TOKEN + email);
            if (!b){
                response.setStatus(4001);
                return false;
            }
            response.setStatus(200);
            return true;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}
